package client

import (
	"errors"
	"gitee.com/byx_darwin/ncloud-go/core"
	"gitee.com/byx_darwin/ncloud-go/core/net/consts"
	"gitee.com/byx_darwin/ncloud-go/services/edge/overseas_ip/apis"
	"github.com/bytedance/sonic"
)

type IPClient struct {
	core.NCloudClient
}

func NewIPClient(credential *core.Credential) *IPClient {
	if credential == nil {
		return nil
	}
	config := core.NewConfig()
	config.SetScheme(consts.SchemeHttps)
	config.SetEndpoint("overseas.ip.api.xyunjs.com")
	//config.SetScheme(consts.SchemeHttp)
	//config.SetEndpoint("43.153.215.129:20005")
	return &IPClient{
		core.NCloudClient{
			Credential:  *credential,
			Config:      *config,
			ServiceName: "public",
			Revision:    core.Version,
			Logger:      core.NewDefaultLogger(core.LogInfo),
		}}
}
func (c *IPClient) DisableLogger() {
	c.Logger = core.NewDummyLogger()
}
func (c *IPClient) QueryRegion(request *apis.QueryRegionGetRequest) (*apis.QueryRegionGetResponse, error) {
	resp, err := c.Send(request.Method, request.GetPath(), "")
	if err != nil {
		return nil, err
	}
	jsonResp := &apis.QueryRegionGetResponse{}

	err = sonic.Unmarshal(resp, jsonResp)
	if err == nil {
		return jsonResp, nil
	}
	errResp := &apis.ErrResponse{}
	err = sonic.Unmarshal(resp, errResp)
	if err == nil {
		c.Logger.Log(core.LogError, "track_id: %s", errResp.TrackID)
		return nil, errors.New(errResp.Msg)
	}
	c.Logger.Log(core.LogError, "Unmarshal json failed, resp: %s", string(resp))
	return nil, err
}

func (c *IPClient) QueryLine(request *apis.LineGetRequest) (*apis.QueryLineGetResponse, error) {
	resp, err := c.Send(request.Method, request.GetPath(), "")
	if err != nil {
		return nil, err
	}
	jsonResp := &apis.QueryLineGetResponse{}

	err = sonic.Unmarshal(resp, jsonResp)
	if err == nil {
		return jsonResp, nil
	}
	errResp := &apis.ErrResponse{}
	err = sonic.Unmarshal(resp, errResp)
	if err == nil {
		c.Logger.Log(core.LogError, "track_id: %s", errResp.TrackID)
		return nil, errors.New(errResp.Msg)
	}
	c.Logger.Log(core.LogError, "Unmarshal json failed, resp: %s", string(resp))
	return nil, err
}
